package com.cui.project.controller;

import cn.hutool.core.collection.CollUtil;
import com.api.common.common.BaseResponse;
import com.api.common.common.ErrorCode;
import com.api.common.common.ResultUtils;
import com.api.common.model.entity.InterfaceInfo;
import com.api.common.model.entity.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cui.project.annotation.AuthCheck;
import com.cui.project.constant.UserConstant;
import com.cui.project.service.InterfaceInfoService;
import com.cui.project.service.UserService;
import com.cui.project.exception.BusinessException;
import com.cui.project.recommend.model.dto.PlacementItem;
import com.cui.project.recommend.model.dto.RecommendItem;
import com.cui.project.recommend.service.PlacementService;
import com.cui.project.recommend.service.RecommendService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/reco")
@RequiredArgsConstructor
public class RecommendController {

    private final RecommendService recommendService;
    private final PlacementService placementService;
    private final UserService userService;
    private final InterfaceInfoService interfaceInfoService;


    /**
     * 个性化推荐
     */
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> list(@RequestParam(defaultValue = "10") int topK, HttpServletRequest request) {

        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        List<RecommendItem> recommendItems = recommendService.recommendForUser(user.getId(), topK);
        if(CollUtil.isEmpty(recommendItems)){
            return ResultUtils.success( new ArrayList<>());
        }
        List<Long> interfaceIds = recommendItems.stream().map(RecommendItem::getInterfaceId).collect(Collectors.toList());

        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "name","imageUrl");
        queryWrapper.in("id",interfaceIds);
        return ResultUtils.success(interfaceInfoService.list(queryWrapper));
    }

    /** 智能运营位（趋势/飙升/新品） */
    @GetMapping("/placements")
    public List<PlacementItem> placements(
                                          @RequestParam(defaultValue = "5") int eachTopK, HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        return placementService.placementsForUser(user.getId(), eachTopK);
    }

    /** 手动重建（也有定时构建） */
    @PostMapping("/rebuild")
    @AuthCheck(mustRole = "admin")
    public String rebuild() {
        recommendService.rebuildModels();
        return "ok";
    }

    /** 收藏/取消收藏 */
    @PostMapping("/favorite/toggle")
    @AuthCheck(anyRole = {UserConstant.ADMIN_ROLE,UserConstant.DEFAULT_ROLE})
    public BaseResponse<String> toggleFavorite(@RequestBody Map<String,Object> body){
        Long userId = Long.valueOf(body.get("userId").toString());
        Long interfaceId = Long.valueOf(body.get("interfaceId").toString());
        boolean enable = Boolean.parseBoolean(body.get("enable").toString());
        recommendService.favorite(userId, interfaceId, enable);
        return ResultUtils.success("ok");
    }
}